/* t_thread.cpp : test dgnsc thread
 * Copyright (C) 2009-2010 drangon <drangon.zhou@gmail.com>
 * 2009-05
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <dgnsc/common.h>
#include <dgnsc/thread.h>

#include "gtest.h"

#include <stdio.h>

// #include <windows.h>

static void thread_func( dgn_thread_t th, void * arg )
{
	dgn_mutex_t mutex = (dgn_mutex_t)arg;
	int i;
	for( i = 0; i < 3; i++ ) {
		dgn_mutex_lock( mutex );
		printf( "thd [%d] enter,  i %d\n", (int)(intptr_t)th % 100, i );
		dgn_sleepms( 160 );
		printf( "thd [%d] leave,  i %d\n", (int)(intptr_t)th % 100, i );
		dgn_mutex_unlock( mutex );
		dgn_sleepms( 50 );
	}
	return;
}

static void thread_func2( dgn_thread_t th, void * arg )
{
	while( dgn_thread_is_running( th ) != 0 ) {
		dgn_sleepms( 1 );
	}
	printf( "in thread, is_running == 0\n" );
	return;
}

TEST( thread, thread )
{
	dgn_thread_t th[3];
	dgn_mutex_t mutex = dgn_mutex_init();
	int i;
	for( i = 0; i < 3; i++ ) {
		th[i] = dgn_thread_init( thread_func, mutex, NULL );
		printf( "th[%d] is %d\n", i, (int)(intptr_t)th[i] );
	}
	dgn_sleepms( 1000 );
	for( i = 0; i < 3; i++ ) {
		dgn_thread_fini( th[i] );
	}
	dgn_mutex_fini( mutex ), mutex = NULL;

	dgn_thread_t th2 = dgn_thread_init( thread_func2, 0, NULL );
	int running = dgn_thread_is_running( th2 );
	printf( "out thread, is_running == %d\n", running );
	dgn_thread_signal_stop( th2 );
	dgn_sleepms( 1000 );
	dgn_thread_fini( th2 );
	printf( "fini thread ok\n" );
}

